package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录检查
//extend HandlerInterceptorAdapter 适配器
//implements  HandlerInterceptor
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //检查当前用户是否登录
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

     /*   //获取当前请求的方法
        // springmvc启动时将所有映射方法封装成HandlerMethod 对象
       //1:获取token
        String token = CookieUtil.getToken(request, response);
        //2:通过token 查redis进行查询用户对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //3:判断用户对象是否存在,如果不存在,直接登录页面
        if (user == null){
            response.sendRedirect("/login.html");
            return false;
        }
*/
        //RequireLogin
        //1:获取当前请求方法对象
        //拦截器可以拦截所有请求,包括动态,静态
        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getUserByToken(token);

        if(handler instanceof HandlerMethod){
            HandlerMethod hm =(HandlerMethod)handler;
            //2:判断搞请求方法头顶上贴了RequireLogin
            if (hm.hasMethodAnnotation(RequireLogin.class)){
                //user=userInfoRedisService.getUserByToken(token);
                //3:如果贴了,需要进行登录检查
                if(user == null){
                    response.sendRedirect("/login.html");
                    return  false;
                }
            }
        }
        //4:如果没贴,直接放行
        //让所有请求,都可以共享用户对象信息
        request.getSession().setAttribute("userInfo",user);
        //如果没贴, 直接放行
        return true;
    }
}
